<?php


namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Task extends Controller
{

    //逾期项目判断
    public function getSet(){
        $where['library'] = 2;
        $where['start_status'] = 1;
        $where['plan_onstream_time'] = ['neq',''];
        $list = Db::name("project_pro")->where($where)->field("id,title,plan_onstream_time")->order("id desc")->select();
        $nowTime = date("Y-m-d");
        $common = new Common();
        $yuqi = 0;

        foreach ($list as $k=>$v){
            $v['plan_onstream_time'] = str_replace(".","-",$v['plan_onstream_time']);
            $v['plan_onstream_time'] = str_replace("/","-",$v['plan_onstream_time']);
            $days = $this->diffBetweenTwoDays($nowTime,$v['plan_onstream_time']);
            $list[$k]['days'] = $days;
            if($days>0){
                $UpdateComment['start_status'] = 3;
                $common->public_select("project_pro",['id'=>$v['id']])->update($UpdateComment);
                $yuqi++;
            }
        }


        echo "逾期项目".$yuqi;
    }


    //招商签约提醒
    public function signProject(){
        $where['library'] = 1;
        $where['signTime'] = ['neq',''];
        $list = Db::name("project_pro")->where($where)->field("id,title,signTime,earlyWarning")->order("id desc")->select();
        $nowTime = date("Y-m-d");
        $common = new Common();
        $yujing = 0;
        $baojing = 0;
        foreach ($list as $k=>$v){
            if(!empty($v['signTime'])){
                $v['signTime'] = str_replace(".","-",$v['signTime']);
                $list[$k]['days'] = $days = $this->diffBetweenTwoDays($nowTime,$v['signTime']);
                $earlyWarning = 0;
                if($days>0 && $v['earlyWarning']==0){
                    $earlyWarning = 1;
                    $addComment['title'] = "签约预警";
                    $addComment['content'] = $v['title']."项目已经签约逾期，请重点关注";
                    $remark = "您的项目已经超过计划签约时间";
                    $yujing++;
                }
                if($days>61 && $v['earlyWarning']!=2){
                    $earlyWarning = 2;
                    $addComment['title'] = "签约报警";
                    $remark = "您的项目已经超过计划签约时间2个月";
                    $addComment['content'] = $v['title']."项目已经超过计划签约时间2个月，请重点关注";
                    $baojing++;
                }
                //更新项目状态
                if(!empty($earlyWarning)){
                    //消息提醒
                    $addComment['pro_id'] = $v['id'];
                    $addComment['addtime'] = date("Y-m-d H:i:s");
                    $addComment['add_id'] =  -1;
                    $addComment['type'] = 2;
                    $common->handle("project_pro_comment",$addComment);
                    $UpdateComment['sign'] = 3;
                    $UpdateComment['earlyWarning'] = $earlyWarning;
                    $common->public_select("project_pro",['id'=>$v['id']])->update($UpdateComment);
                    $notice = new Notice();
                    $notice->signMessage($addComment,$remark);
                }
            }
        }
        echo "预警项目".$yujing."报警项目".$baojing;
    }

    //计算相差天数
    function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
//        if ($second1 < $second2) {
//            $tmp = $second2;
//            $second2 = $second1;
//            $second1 = $tmp;
//        }
        return ($second1 - $second2) / 86400;
    }


    //更改项目逾期状态
    public function projectApi(){
        $where['library'] = 4;
        $where['id'] = ['gt',0];
        $list = Db::name("project_pro")->where($where)->field("id")->select();
        $lastMonth = date('m', strtotime('-1 month'));  //上月
        $planWhere['year'] = date("Y");
        $planWhere['month'] = $lastMonth;
        foreach ($list as $k=>$v){
            $planWhere['pro_id'] = $v['id'];
            $declare = Db::name("project_pro_plandetail")->where($planWhere)->value("declare");
            $list[$k]['declare'] = empty($declare)?'':$declare;


            if($declare==null){
                $project_status = 1;
            }else{
                $project_status = 0;
            }
            //更改项目逾期状态
            Db::name("project_pro")->where(['id'=>$v['id']])->update(['project_status'=>$project_status]);
        }

    }



    //任务（循环下发当天的票）
    public function bill()
    {
        $nowtime = date("Y-m-d");

        $list = Db::name("tickets_list")->where(['effective_time' => ['egt', $nowtime], 'status' => 0])->field("signcode,name,mobile,IDcard,face,effective_time,end_time")->select();

        //$list = Db::name("tickets_list")->where(['id'=>524])->field("signcode,name,mobile,IDcard,face,effective_time,end_time")->select();

        $error = 0;
        $isok = 0;
        $commonDevice = new Test();
        $token = $commonDevice->token();
        foreach ($list as $k => $v) {
            $personsCreate['employeeNo'] = $v['signcode'];
            if (!empty($v['IDcard'])) {
                $cardNos = [$v['IDcard'], $v['signcode']]; //$order['IDcard']
            } else {
                $cardNos = [$v['signcode']];
            }
            $personsCreate['personName'] = empty($v['name']) ? "欢迎光临" : $v['name'];

            $startTime = date("Y-m-d\TH:i:sP", strtotime($v['effective_time']));
            $endtTime = date("Y-m-d\T23:59:59P", strtotime($v['end_time']));
            $personsCreate['validBeginTime'] = $startTime;
            $personsCreate['validEndTime'] = $endtTime;

////            $personFace = $commonDevice->personFace($personsCreate['employeeNo'],$token);
            $cardValue = $commonDevice->cardAdd($personsCreate, $cardNos);

            //更新人脸
            if (!empty($v['face']) & $v['face'] != 'null') {
                $personsCreate1['verifyImage'] = false;
                $personsCreate1['faceImageBase64'] = $v['face'];
                $personsCreate1['employeeNo'] = $personsCreate['employeeNo'];
                $personsCreate1['personName'] = empty($v['name']) ? "欢迎光临" : $v['name'];
                $personsCreate1['validBeginTime'] = $startTime;
                $personsCreate1['validEndTime'] = $endtTime;
                $cardValue = $commonDevice->personsUpdate($personsCreate1);
            }

            if ($cardValue !== true) {
                $error++;
            } else {
                $isok++;
            }
        }
        $black = "推送失败" . $error . "张,推送成功" . $isok . "张";
        return $black;
    }

    /**
     * 批量删除过期人员
     * @author zhixuedong
     * @date 2021/2/19/019
     */
    public function batchDel()
    {
        $commonDevice = new Test();
        //获取token
        $token = $commonDevice->token();
        $list = $commonDevice->getEmployeeNos();
        $list = $list['data']['rows'];
        $nowtime = time();
        $isok = 0;
        foreach ($list as $item) {
            $employeeNo = $item['employeeNo'];
            $black = $commonDevice->personFace($employeeNo, $token);
            if ($black['code'] == 200) {
                $detail = $black['data'];
                $validEndTime = strtotime($detail['validEndTime']);
                if ($nowtime > $validEndTime) {
                    $isok++;
                    Db::name("tickets_list")->where(['signcode' => $employeeNo])->update(['status' => 2]);
                    //删除人员
                    $commonDevice->personsDelete($employeeNo, $token);
                    //删除卡号
                    $commonDevice->deletePersonCards([$employeeNo], $employeeNo, $token);
                    //权限组人员解绑
                    $commonDevice->removePersons([$employeeNo], $token);
                }
            }
        }
        echo "操作成功,删除人数" . $isok;
    }

    /**
     * 拉取设备事件
     * @throws Exception
     * @throws \think\exception\PDOException
     * @author zhixuedong
     * @date 2021/2/25/025
     */
    public function deviceList(){
        try {
            $commonDevice = new Test();
            $token = $commonDevice->token();
            $startTime = date("Y-m-d\TH:i:sP",time());
            $endtTime = date("Y-m-d\TH:i:sP",strtotime('-2minute',time()));
            $startTime = urlencode($startTime);
            $endtTime = urlencode($endtTime);
//        $major = [1,6,7,8,9,21,22,75,76,1024];
            $major = [1,75];
            $devicesList = $commonDevice->devicesList();

            $majordesc = ['1'=>'刷卡开锁','75'=>'人脸开锁','21'=>'门锁打开'];

            $i = 0;

            foreach ($devicesList['data']['rows'] as $key=>$val){
                $i++;
                foreach ($major as $k=>$v){
                    $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/accessEvents/actions/list?pageNo=1&pageSize=100&deviceSerial=".$val['deviceSerial']."&major=5&minor=".$v."&startTime=".$startTime."&endTime=".$endtTime;
                    $html = '';
                    $html = $commonDevice->curl_file_get_contents($url,$token['access_token']);
                    $html = json_decode($html,true);

//                echo $val['deviceSerial'];
//                dump($html);

                    if($html['code']==200){
                        foreach ($html['data']['rows'] as $k1=>$v1){
                            $log['date_time'] = $v1['time'];
                            $log['employee_no'] = $v1['employeeNo'];
                            $log['card_no'] = $v1['cardNo'];
                            $log['device_serial'] = $val['deviceSerial'];
                            $log['device_name'] = $val['deviceSerial'];
                            $log['type'] = $v;
                            $log['description'] = $majordesc[$v];
                            $log['code'] = date("Ymd").$v1['serialNo'];

                            $id = Db::name("tickets_device_log")->where(['code'=>$log['code']])->value("id");
                            if(empty($id)){
                                Db::name("tickets_device_log")->insert($log);
                                //检票次数减一
                                $tickets['signcode'] = $v1['employeeNo'];
                                $degree = Db::name("tickets_list")->where($tickets)->value("degree");
                                if($degree>0){
                                    $update = [];
                                    $update['degree'] = $degree-1;
                                    $update['check_time'] = time();
                                    if($degree==0){
                                        $update['status'] = 2;
                                        $commonDevice->cartDel($v1['employeeNo']);
                                    }
                                    Db::name("tickets_list")->where($tickets)->update($update);
                                }
                            }
                        }
                    }else{
                        break;
                    }
//                    if($i==2){die;}
                }
            }
            echo "操作成功";
        }catch (Exception $e){
            echo "日志中断";
        }

    }


}